package com.inhim.pjhim.view;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.inhim.pjhim.R;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.utils.Util;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.facebookmessenger.FacebookMessenger;
import cn.sharesdk.facebookmessenger.FacebookMessengerClientNotExistException;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;


public class ShareDialog extends Dialog {
    private static int mTargetScene = SendMessageToWX.Req.WXSceneSession;
    private static int mTargetScene1 = SendMessageToWX.Req.WXSceneTimeline;

    private View llQR;
    private View btnSave;
    private View llWeChart;
    private View llCircle;
    private View llFacebook;
    private View llMessager;

    public ShareDialog(Context context) {
        super(context);
        init();
    }

    public ShareDialog(Context context, int themeResId) {
        super(context, themeResId);
        init();
    }

    protected ShareDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        init();
    }

    private void init() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dialog_share);
        //获取当前Activity所在的窗体
        Window dialogWindow = this.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0); //消除边距

        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.y = 0;//设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);

        llQR = findViewById(R.id.llQR);
        btnSave = findViewById(R.id.btnSave);
        llWeChart = findViewById(R.id.llWeChart);
        llCircle = findViewById(R.id.llCircle);
        llFacebook = findViewById(R.id.llFacebook);
        llMessager = findViewById(R.id.llMessager);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.qr_share);
                saveBmp2Gallery(getContext(), bitmap, "inHimApp");
            }
        });

        llWeChart.setOnClickListener(view -> {
            if (listener != null) {
                listener.onItemClick(ShareType.Wechart);
            }
        });
        llCircle.setOnClickListener(view -> {
            if (listener != null) {
                listener.onItemClick(ShareType.FriendCircle);
            }
        });
        llFacebook.setOnClickListener(view -> {
            if (listener != null) {
                listener.onItemClick(ShareType.Facebook);
            }
        });
        llMessager.setOnClickListener(view -> {
            if (listener != null) {
                listener.onItemClick(ShareType.Messager);
            }
        });
    }

    public ShareDialog setQrVisible(boolean show) {
        llQR.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
        return this;
    }

    public void doDefaultAction(boolean showQr, String url, String title, String description) {
        setQrVisible(showQr);
        setListener(new Listener() {
            @Override
            public void onItemClick(ShareType shareType) {
                if (shareType == ShareType.Wechart) {
                    wecharShare(false, url, title, description);
                } else if (shareType == ShareType.FriendCircle) {
                    wecharShare(true, url, title, description);
                } else if (shareType == ShareType.Facebook) {
                    facebookShare(url, title, description);
                } else if (shareType == ShareType.Messager) {
                    messagerShare(url, title, description);
                }
                dismiss();
            }
        });
    }

    public enum ShareType {
        Wechart,
        FriendCircle,
        Facebook,
        Messager
    }

    private Listener listener;

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public interface Listener {
        void onItemClick(ShareType shareType);
    }

    @Override
    public void show() {

        super.show();
    }

    /**
     * @param bmp     获取的bitmap数据
     * @param picName 自定义的图片名
     */
    public static void saveBmp2Gallery(Context context, Bitmap bmp, String picName) {
//        saveImageToGallery(bmp,picName);
        String fileName = null;
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;


        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;
        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");
            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);

        BToast.showText("图片保存成功");
    }


    public void wecharShare(boolean isMonment, String url, String title, String description) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        Bitmap bmp = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        if (!isMonment) {
            req.scene = mTargetScene;
        } else {
            req.scene = mTargetScene1;
        }
        MyApplication.api.sendReq(req);
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public void facebookShare(String url, String title, String description) {
        Platform platform = ShareSDK.getPlatform(Facebook.NAME);
        Platform.ShareParams shareParams = new Platform.ShareParams();
        shareParams.setHashtag(title);
        shareParams.setQuote(description);
        shareParams.setUrl(url);
        shareParams.setShareType(Platform.SHARE_WEBPAGE);
        platform.setPlatformActionListener(platformActionListener);
        platform.share(shareParams);
    }

    public void messagerShare(String url, String title, String description) {
        Platform platform = ShareSDK.getPlatform(FacebookMessenger.NAME);
        Platform.ShareParams shareParams = new Platform.ShareParams();
        shareParams.setTitle(title);
        shareParams.setText(description);
        shareParams.setHashtag(title);
        shareParams.setQuote(description);
        shareParams.setUrl(url);
//        shareParams.setim
        shareParams.setShareType(Platform.SHARE_WEBPAGE);
        platform.setPlatformActionListener(platformActionListener);
        platform.share(shareParams);
    }

    private void showText(String message) {
        Observable.just(message)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    BToast.showText(s);
                });
    }

    private final PlatformActionListener platformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            showText("分享成功");
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            if (TextUtils.isEmpty(throwable.getMessage())) {
                if (throwable instanceof FacebookMessengerClientNotExistException) {
                    showText("目前您的FacebookMessenger版本过低或未安装，需要安装才能使用");
                } else if (throwable instanceof WechatClientNotExistException) {
                    showText("目前您的微信版本过低或未安装，需要安装才能使用");
                } else {
                    showText("分享失败！");
                }
            } else {
                showText(throwable.getMessage());
            }

        }

        @Override
        public void onCancel(Platform platform, int i) {
            showText("取消分享");
        }
    };
}
